export const stateTypes = {
  isAdminLogin: "isAdminLogin",
  loginInfo: "loginInfo",
  token: "token",
  menuCollapse: "menuCollapse",
  menuList: "menuList",
  currentMenu: "currentMenu"
};

export const state = () => ({
  isAdminLogin: false,
  loginInfo: {},
  token: "",
  menuCollapse: false,
  menuList: [],
  currentMenu: []
});

export const mutationsTypes = {
  setCurrentMenu: "setCurrentMenu",
  setToken: "setToken",
  setLoginInfo: "setLoginInfo"
};

export const mutations = {
  setLoginInfo(state, payload) {
    state.loginInfo = payload;
  },
  setToken(state, payload) {
    state.token = payload;
    if (payload) {
      state.isAdminLogin = true;
    } else {
      state.isAdminLogin = false;
    }
  },
  setMenuCollapse(state, payload) {
    state.menuCollapse = payload;
  },
  setMenuList(state, payload) {
    state.menuList = payload;
  },
  setCurrentMenu(state, { url }) {
    const list = state.menuList;
    const where = r => {
      return url && r.url === url;
    };
    const find = (arr, whereFn, result) => {
      for (let i = 0; i < arr.length; i++) {
        const item = arr[i];
        if (whereFn(item)) return [...result, item];
        if (item.children && item.children.length) {
          const res = find(item.children, whereFn, [...result, item]);
          if (res) return res;
        }
      }
    };
    state.currentMenu = find(list, where, []) || [];
  }
};

export const actionsTypes = {
  getMenuList: "getMenuList",
  getLoginInfo: "getLoginInfo"
};
export const actions = {
  async getMenuList({ commit }, payload) {
    const list = await this.$adminService.menuList({
      type: "tree",
      fid: 0
    });
    commit("setMenuList", list);
  },

  async getLoginInfo({ commit }, payload) {
    const data = await this.$adminService.token(payload);
    if (data && data.id) commit(mutationsTypes.setLoginInfo, data);
    else throw new Error("token 失效");
  }
};
